//
// Copyright © 2021 dev. All rights reserved.
// 

import Cocoa
import RxSwift
import ConfCore
import RealmSwift
import os.log

enum DownloadStatus {
    case none
    case downloading(DownloadManager)
}

class DownloadManager: NSObject {
    static let shared: DownloadManager = DownloadManager()
    private let defaults = UserDefaults.standard
    private let log = OSLog(subsystem: "WWDC", category: "DownloadManager")
    static let downloadQuality = SessionAssetType.hdVideo
    private let configuration = URLSessionConfiguration.background(withIdentifier: "WWDC Video Downloader")
    private var backgroundSession: Foundation.URLSession!
    var downloadTasks: [String:Download]   = [:]{
        didSet {
            downloadTasksSubject.onNext(Array(downloadTasks.values))
        }
    }
    private let downloadTasksSubject = BehaviorSubject<[Download]>(value: [])
    var downloadObservable: Observable<[Download]> {
        return  downloadTasksSubject.asObservable();
    }
    var storage:Storage!
    override init() {
        super.init()
        backgroundSession = URLSession(configuration: configuration,delegate: self,delegateQueue: .main)

    }

    func start(with storage:Storage)  {
        self.storage = storage
        backgroundSession.getTasksWithCompletionHandler { _, _, pendingTasks in
            for task in pendingTasks {
                if let key = task.originalRequest?.url?.absoluteString,
                   let remoteURL = URL(string: key){

                }
            }
        }
    }

}


// MARK: - URLSessionDelegate
extension DownloadManager:URLSessionDownloadDelegate, URLSessionTaskDelegate {
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {

    }


}

extension DownloadManager {
    struct Download:Equatable {

    }
}


extension NotificationCenter {
    func dm_addObserver<T:Equatable>(forName name:NSNotification.Name, filteredBy object: T, using block: @escaping (T)-> Void) -> NSObjectProtocol {
        return self.addObserver(forName: name, object: nil, queue: .main) { note in
            guard object == note.object as? T else {return}
            block(object)
        }
    }
}
